package com.mk.service.impl;

import com.mk.common.Config;
import com.mk.common.JwtUserFactory;
import com.mk.mapper.RoleMapper;
import com.mk.mapper.UserMapper;
import com.mk.model.entity.Role;
import com.mk.model.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 3:09 PM 3/13/18
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUserNameForLogin(username, Config.ABLE_CONFIG.ABLE);
        List<Role> roles = roleMapper.findRoleByUsername(username,Config.ABLE_CONFIG.ABLE);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            return JwtUserFactory.create(user,roles);
        }
    }
}
